<template>
    <div class="page-container">

        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleTabsClick">
            <el-tab-pane label="小程序设置" name="first"></el-tab-pane>
            <el-tab-pane label="主题模板" name="second"></el-tab-pane>
        </el-tabs>

        <div v-if="activeName == 'first'">
            <el-form :model="search" :rules="rules" size="small" ref="searchForm">
                <el-form-item label="小程序名称:" prop="name">
                    <el-input placeholder="请输入模板名称" v-model="search.name" clearable></el-input>
                </el-form-item>
                <el-form-item label="appid:" prop="appid">
                    <el-input placeholder="请输入appid" v-model="search.appid" clearable></el-input>
                </el-form-item>
                <el-form-item label="AppSecret:" prop="appsecret">
                    <el-input placeholder="请输入AppSecret" v-model="search.appsecret" clearable></el-input>
                </el-form-item>
                <el-form-item label="商户号:" prop="merchantNumber">
                    <el-input placeholder="请输入商户号" v-model="search.merchantNumber" clearable></el-input>
                </el-form-item>
                <el-form-item label="支付秘钥:" prop="partnerKey">
                    <el-input placeholder="请输入支付秘钥" v-model="search.partnerKey" clearable></el-input>
                </el-form-item>
                <el-form-item label="上传秘钥:" prop="payFileUrl">
                    <el-upload class="upload-demo" :action="uploadUrl" :file-list="fileList" :headers="headers"
                        :on-success="uploadOnSuccess">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div class="el-upload__tip">只能上传p12文件</div>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveSubmit(searchForm)">保存</el-button>
                </el-form-item>
            </el-form>
        </div>


        <div v-if="activeName == 'second'">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <span></span>
                        <el-button class="button" type="primary" @click="saveTempSubmit(searchForm)">保 存</el-button>
                    </div>
                </template>
                <div>
                    <el-form :model="form" size="small">
                        <el-form-item label="选择主题模板:">
                            <el-radio-group v-model="form.tempId" @change="selectTemp">
                                <el-radio v-for="(item, index) in tempOptions" :label="item.id" :key="index">{{ item.tempName }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="模板展示:">
                            <el-image style="width: 250px; height: 500px" :src="form.previewUrl" fit="fit" />
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>


        </div>
    </div>
</template>
  
<script>
import { reactive, toRefs, onMounted, ref } from 'vue'
import WeChatTempDetail from '../components/WeChatTempDetail.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getList as getTempList, getMerchantsRelationByMerchantsId, createMerchantsRelation, updateMerchantsRelation } from '/@/api/pms/wechatTemp'
import { getBymerchantsId, update, create } from '/@/api/pms/applicationSetting'
import { Session } from '/@/utils/storage'
import api from '/@/api/commonApi'
export default {
    name: 'HomeAdv',
    components: {
        WeChatTempDetail
    },
    setup() {
        const state = reactive({
            activeName: 'first',
            uploadUrl: '/api/file/filaAttach/upload',
            headers: {
                '17work': Session.get('token')
            },
            fileList: [],
            list: [],
            search: {
                current: 1,
                size: 10
            },
            title: '新增',
            form: {},
            dialogFormVisible: false,
            total: 100,
            current: 1,
            page: 10,
            statusOptions: [
                {
                    value: '0',
                    label: '未发布',
                },
                {
                    value: '1',
                    label: '已发布',
                },
            ],
            rules: {
                name: [{
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                }],
                appid: [{
                    required: true,
                    message: '请输入appid',
                    trigger: 'blur'
                }],
                appsecret: [{
                    required: true,
                    message: '请输入appsecret',
                    trigger: 'blur'
                }],
                merchantNumber: [{
                    required: true,
                    message: '请输入商户号',
                    trigger: 'blur'
                }],
                partnerKey: [{
                    required: true,
                    message: '请输入收款秘钥',
                    trigger: 'blur'
                }],
                payFileUrl: [{
                    required: true,
                    message: '请上传秘钥',
                    trigger: 'blur'
                }],
            },
            tempOptions: [],
            nowSelectForm:{}
        })
        const searchForm = ref()
        const add = () => {
            restForm()
            state.title = '新增应用模板'
            state.dialogFormVisible = true
        }
        const editRow = row => {
            state.title = '编辑应用模板'
            get(row.id).then(res => {
                state.form = res.data
                let previewUrl = []
                if (state.form.previewUrl != null) {
                    previewUrl.push({
                        name: 'images',
                        url: res.data.previewUrl
                    })
                }
                state.form.backageImage = previewUrl
            })
            state.dialogFormVisible = true
        }
        const restForm = () => {
            state.form = {
                id: null,
                isCustomize: "0",
                merchantsId: null,
                note: null,
                previewUrl: null,
                status: "0",
                tempId: null,
                tempName: null,
                backageImage: []
            }
        }
        const delRow = row => {
            ElMessageBox.confirm(
                '是否确认删除名称为"' + row.name + '"的数据项？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                remove(row.id).then(res => {
                    if (res.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getList()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '删除失败：' + res.message,
                        })
                    }
                })

            }).catch()
        }
        const getList = () => {
            getTempList().then(res => {
                state.tempOptions = res.data
                getMerchantsRelationByMerchantsId(0).then(res => {
                    if (res.data != null) {
                        state.form = res.data
                        selectTemp(state.form.tempId)
                    }else{
                        // 获取默认的
                        let r = {
                            previewUrl:'',
                            tempName:'',
                            isCustomize:'',
                            authStatus:'0',
                            tempId:null
                        }
                        for (let t of state.tempOptions) {
                            if (t.isDefault == '1') {
                                r.previewUrl = t.previewUrl
                                r.tempName = t.tempName
                                r.isCustomize = t.isCustomize
                                r.authStatus = "0"
                                r.tempId = t.id
                            }
                        }
                        if(r.tempId ==null){
                            let t = state.tempOptions[0]
                            r.previewUrl = t.previewUrl
                            r.tempName = t.tempName
                            r.isCustomize = t.isCustomize
                            r.authStatus = "0"
                            r.tempId = t.id
                        }
                        state.form = r
                    }
                })
            })


        }
        const getAppSetting = () => {
            api.getAppSetting().then(res => {
                if (res.code == 0 && res.data != null) {
                    state.search = res.data
                    let previewUrl = []
                    if (state.search.payFileUrl != null) {
                        previewUrl.push({
                            name: 'apiclient_cert.p12',
                            url: res.data.previewUrl
                        })
                    }
                    state.fileList = previewUrl
                }
            })
        }
        const handleSizeChange = e => {
            state.search.size = e
            getList()
        }
        const handleCurrentChange = e => {
            state.search.current = e
            state.current = e
            getList()
        }
        const onDetailSubmit = () => {
            getList()
            state.dialogFormVisible = false
        }
        const changeStatus = (row) => {
            /* updateStatus({ id: row.id, status: row.status }).then(res => {
                if (res.code == 0) {
                    ElMessage.success('修改成功')
                    getList()
                } else {
                    ElMessage.error('修改失败:' + res.message)
                }
            }) */
        }
        const filterSubmit = () => {
            state.search.current = 1
            getList()
        }
        const reset = () => {
            state.search = {
                current: 1,
                size: 10,
                status: '',
                tempName: ''
            }
            getList()
        }
        const uploadOnSuccess = (response, uploadFiles) => {
            let d = []
            d.push({ name: response.data.name, url: response.data.src })
            state.fileList = d
            state.search.payFileUrl = state.fileList[0].url
        }
        const handleTabsClick = () => {
            if (state.activeName == 'first') {
                getAppSetting()
            } else if (state.activeName == 'second') {
                getList()
            }
        }


        const saveSubmit = async (formEl) => {
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
                    let data = state.search
                    if (state.fileList.length > 0) {
                        data.payFileUrl = state.fileList[0].url
                    } else {
                        data.payFileUrl = null
                    }
                    if (data.id != null && data.id != '') {
                        update(data).then(res => {
                            if (res.code == 0) {
                                ElMessage.success("修改成功");
                            } else {
                                ElMessage.error("修改失败");
                            }
                        })
                    }
                    // 新增
                    else {
                        create(data).then(res => {
                            if (res.code == 0) {
                                ElMessage.success("添加成功");
                            } else {
                                ElMessage.error("添加失败");
                            }
                        })

                    }
                }
            })

        }


        const selectTemp = (val) => {
            for (let t of state.tempOptions) {
                if (t.id == val) {
                    state.form.previewUrl = t.previewUrl
                    state.form.tempName = t.tempName
                    state.form.isCustomize = t.isCustomize
                    state.form.authStatus = "0"
                    state.form.tempId = t.id
                }
            }

        }

        const saveTempSubmit = async () => {
            let data = state.form
            if (data.id != null && data.id != '') {
                updateMerchantsRelation(data).then(res => {
                    if (res.code == 0) {
                        ElMessage.success("修改成功");
                    } else {
                        ElMessage.error("修改失败");
                    }
                })
            }
            // 新增
            else {
                data.merchantsId = 0
                createMerchantsRelation(data).then(res => {
                    if (res.code == 0) {
                        ElMessage.success("添加成功");
                    } else {
                        ElMessage.error("添加失败");
                    }
                })

            }


        }


        onMounted(() => {
            handleTabsClick()
        })
        return {
            add,
            editRow,
            delRow,
            handleSizeChange,
            handleCurrentChange,
            onDetailSubmit,
            restForm,
            changeStatus,
            filterSubmit,
            reset,
            uploadOnSuccess,
            getAppSetting,
            searchForm,
            saveSubmit,
            handleTabsClick,
            selectTemp,
            saveTempSubmit,
            ...toRefs(state)
        }
    }
}
</script>
  
<style lang="scss" scoped>
.page-container {
    .table-list {
        background: var(--next-color-white);
        margin-top: 10px;

        :deep(.el-table__header-wrapper .el-table__cell) {
            background: var(--el-color-primary-light-9);
            color: var(--next-bg-menuBar-light-1);
        }
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
</style>